import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutterapp/src/bean/bean_user.dart';
import 'package:flutterapp/src/net/dio_utils.dart';
import 'package:flutterapp/src/page/common/user_helper.dart';
import 'package:flutterapp/src/page/login/bg/bubble_widget.dart';
import 'package:flutterapp/src/page/login/custom_textfield_widget.dart';
import 'package:flutterapp/src/utils/log_utils.dart';
import 'package:flutterapp/src/utils/toast_utils.dart';

class LoginPage extends StatefulWidget {
  final StreamController loginStreamController;
  LoginPage(this.loginStreamController);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 密码输入框焦点控制
  FocusNode _passwordFocusNode = new FocusNode();
  // 手机号/用户名输入框焦点控制
  FocusNode _userNameFocusNode = new FocusNode();
  // 手机号输入框控制器
  TextEditingController _userNameEditController = new TextEditingController();
  // 密码输入框控制器
  TextEditingController _userPasswordEditController =
      new TextEditingController();
  // 是否显示密码
  bool _passwordShow = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          width: double.infinity,
          height: double.infinity,
          child: Stack(
            children: [
              //第一层 背景
              buildBackgroundWidget(),
              //第二层 气泡
              Positioned.fill(
                child: BubbleWidget(),
              ),
              //第三层 高斯模糊
              buildFliterWidget(),
              //第四层 logo
              buildLogoWidget(),
              // 第五层 输入框
              buildInputWidget(),
              // 第六层 关闭按钮
              buildCloseWidget(),
            ],
          )),
    );
  }

  // 创建背景
  buildBackgroundWidget() {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          // 线性渐变
          gradient: LinearGradient(
              // 渐变开始方向
              begin: Alignment.topLeft,
              // 渐变结束方向
              end: Alignment.bottomRight,
              // 渐变的颜色组 至少有两个
              colors: [
                Colors.lightBlueAccent.withOpacity(0.3),
                Colors.blue.withOpacity(0.3),
              ]),
        ),
      ),
    );
  }

  // 创建高斯模糊
  buildFliterWidget() {
    return Positioned.fill(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
        child: Container(
          color: Colors.white.withOpacity(0.3),
        ),
      ),
    );
  }

  // 创建logo
  buildLogoWidget() {
    return Positioned(
      top: 120,
      left: 0,
      right: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Hero(
            tag: "logo",
            child: Material(
              color: Colors.transparent,
              child: ClipOval(
                child: Image.asset("assets/images/app_icon.png",
                    width: 33, height: 33),
              ),
            ),
          ),
          SizedBox(width: 20),
          Text(
            "欢迎光临",
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 22,
              color: Colors.blue,
            ),
          )
        ],
      ),
    );
  }

  // 构建关闭按钮
  buildCloseWidget() {
    return Positioned(
      left: 20,
      top: 20,
      child: CloseButton(
        color: Colors.white,
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  // 构建输入框与单选框
  buildInputWidget() {
    return Positioned(
      left: 60,
      right: 60,
      bottom: 60,
      child: Column(
        children: [
          //手机号
          TextFieldWidget(
            hintText: "手机号",
            submit: (value) {
              if (value.length != 11) {
                ToastUtils.showToast("请输入11位手机号");
                //手机号输入框重新获取焦点
                FocusScope.of(context).requestFocus(_userNameFocusNode);
                return;
              }
              //手机号输入框失去焦点
              _userNameFocusNode.unfocus();
              //密码输入框获取焦点
              FocusScope.of(context).requestFocus(_passwordFocusNode);
            },
            focusNode: _userNameFocusNode,
            prefixIconData: Icons.phone,
            controller: _userNameEditController,
            obscureText: false,
          ),
          SizedBox(
            height: 40,
          ),
          //密码

          TextFieldWidget(
            // 占位符
            hintText: "密码",
            // 提交事件
            submit: (value) {
              if (value.length < 6) {
                ToastUtils.showToast("请输入6位以上密码");
                //密码输入框获取焦点
                FocusScope.of(context).requestFocus(_passwordFocusNode);
                return;
              }
              //手机号输入框失去焦点
              _userNameFocusNode.unfocus();
              //密码输入框失去焦点
              _passwordFocusNode.unfocus();
            },
            // 焦点控制器
            focusNode: _passwordFocusNode,
            // 左侧图标占位
            prefixIconData: Icons.lock_open_outlined,
            // 右侧图标占位
            suffixIconData:
                _passwordShow ? Icons.visibility : Icons.visibility_off,
            // 是否显示右侧图标
            obscureText: _passwordShow,
            // 输入框控制器
            controller: _userPasswordEditController,
            // 右侧图标点击事件
            onTap: () {
              //设置密码输入框输入内容可见与不可见
              setState(() {
                _passwordShow = !_passwordShow;
              });
            },
          ),
          // 登录按钮
          SizedBox(height: 40),
          Container(
            height: 44,
            width: double.infinity,
            child: ElevatedButton(
              child: Text("登录", style: TextStyle(fontSize: 18)),
              onPressed: () {
                LogUtils.e("点击了登录");
                submitFunction();
              },
            ),
          ),
          // 注册按钮
          SizedBox(height: 20),
          Container(
            height: 44,
            width: double.infinity,
            child: ElevatedButton(
              child: Text("注册", style: TextStyle(fontSize: 18)),
              onPressed: () {
                LogUtils.e("点击了注册");
              },
            ),
          ),
        ],
      ),
    );
  }

  ///登录功能
  void submitFunction() async {
    //获取用户名
    String userName = _userNameEditController.text;
    //获取密码
    String password = _userPasswordEditController.text;

    if (userName.trim().length != 11) {
      ToastUtils.showToast("请输入11位手机号");
      return;
    }
    if (password.trim().length < 6) {
      ToastUtils.showToast("请输入6位以上密码");
      return;
    }

    Map<String, dynamic> map = {
      "mobile": userName,
      "password": password,
    };

    //网络请求 发起 post 请求
    // ResponseInfo responseInfo = await DioUtils.instance.postRequest(
    //   //请求地址
    //   url: HttpHelper.login,
    //   //请求参数
    //   formDataMap: map,
    // );
    //模拟登录成功
    ResponseInfo responseInfo =
        await Future.delayed(Duration(milliseconds: 1000), () {
      return ResponseInfo(data: {
        "userName": "测试数据",
        "age": 22,
      });
    });
    //响应成功
    if (responseInfo.success) {
      //解析数据
      UserBean userBean = UserBean.fromMap(responseInfo.data);
      //内存保存数据
      UserHelper.getInstance.userBean = userBean;
      //提示框
      ToastUtils.showToast("登录成功");
      //关闭当前页面
      Navigator.of(context).pop(true);
      //发送消息更新我的页面显示内容
      widget.loginStreamController.add(0);
    } else {
      //登录失败页面小提示
      ToastUtils.showToast("${responseInfo.message}");
    }
  }
}
